#include "../myfastdo/myfastdo.hpp"
#include "../protocol_dist.hpp"
#include "../utils.hpp"
USING_ALL;

String getPath(MyFastdoServer &SERV, String const &path)
{
    return SERV.REQ.doDirPath + "/uploads/" + path;
}

// 获取 gender 的列表。
FASTDO_API void ActionMain(MyFastdoServer &SERV)
{
    if (!SERV.user.isLogged())
    {
        throw RequestError("NOT_LOGGED");
    }

    // 接收数据format
    Mixed fileInfo = SERV.REQ.post.getVars()["file_info"];
    String replace = (String)SERV.REQ.post.getVars()["replace"];
    if (fileInfo.isNull())
    {
        throw RequestError("REQ_ILL", "没有文件");
    }
    String fileName = (String)fileInfo["name"];                         // 文件名
    int size = (int)fileInfo["size"];                                   // 大小
    String mime = (String)fileInfo["mime"];                             // 文件类型。
    String srcPath = (String)fileInfo["path"];                          // 路径。
    String extName = fileName.substr(fileName.find_last_of('.') + 1);   // 获取文件后缀
    String originName = fileName.substr(0, fileName.find_last_of('.')); // 获取文件原名

    Mixed &config = SERV.configUtils.getConfig();

    if (size == 0)
    {
        throw RequestError("ERROR", "文件为空");
    }
    SERV.log("mime:" + mime);
    SERV.log(winux::Format("size(%d) size(%d)", size, (int)config["upload_max_size"]));
    if (size > (int)config["upload_max_size"])
    {
        throw RequestError("ERROR", "文件超出1MB");
    }
    if (!(mime == "image/jpeg" || mime == "image/jpg" || mime == "image/png" || mime == "audio/mp3"))
    {
        throw RequestError("ERROR", "文件格式错误");
    }

    if (mime == "audio/mp3")
    {
        extName = "mp3";
    }
    else if (mime == "image/jpeg" || mime == "image/jpg")
    {
        extName = "jpg";
    }
    else if (mime == "image/png")
    {
        extName = "png";
    }

    if (!replace.empty())
    {
        if (winux::DetectPath(getPath(SERV, replace)))
        {
            winux::CommonDelete(getPath(SERV, replace));
            // winux::RemovePath();
        }
    }
    if (!winux::DetectPath("uploads"))
    {
        winux::MakeDirExists("uploads");
    }
    Mixed userData = SERV.user.getUserData();
    SERV.log("userdata: " + userData.json());
    // 移动文件，
    String dstPath = "";
    // 这个URL是最终记录在数据中的路径。
    uint64 utcTime = GetUtcTimeMs();
    String url = (String)userData["name"] + Format("%llu", utcTime) + "." + extName;
    dstPath = getPath(SERV, url);
    SERV.log("read file: " + srcPath);
    SERV.log("write file: " + dstPath);
    File src(srcPath, "rb");
    File dest(dstPath, "wb");
    winux::Buffer data = src.buffer();
    if (!dest.write(data))
    {
        throw RequestError("ERROR", "写文件失败");
    }
    else
    {
        // todo: 建立数据库记录
    }

    ProtocolS2CUploadFile rtn;
    rtn.ok = true;
    rtn.url = url;
    SERV.data.res.data = rtn.toMixed();
}